import {Direction} from "@/types.ts";
import logo from '../assets/svg/input.svg';

const FAST_FORM_CLASS_NAME = "fast-form-decorator"

/**
 * 检索 window 中的表单 返回数组
 */
function retrieveBodyForm() {
  return document.querySelectorAll("form");
}


/**
 *
 * @param form
 * @param position
 */
function decoratorForm(form: HTMLFormElement, position: Direction) {
  form.querySelectorAll(`.${FAST_FORM_CLASS_NAME}`).forEach(el => el.remove());
  form.style.position = 'relative';
  let decorator = document.createElement("img");
  decorator.style.zIndex = "999";
  decorator.style.width = "30px"
  decorator.style.height = "30px"
  decorator.classList.add(FAST_FORM_CLASS_NAME);
  decorator.src = logo
  decorator.style.position = "absolute";
  decorator.style.top = `0px`; // 相对于form顶端
  decorator.style.left = `${form.clientWidth + 24}px`; // form宽度减图标宽度，靠右边

  // 动画
  const animation = decorator.animate([
    {
      transform: "scale(1)",
    }, {
      transform: "scale(1.2)",
    }
  ], {
    duration: 300,
    fill: 'forwards',
    easing: 'ease-out'
  })


  decorator.addEventListener("click", (e) => {
    e.preventDefault();
    e.stopPropagation();
    retrieveFormInfo(form);
  });

  decorator.addEventListener("mouseenter", (_e) => {
    animation.play();
  })
  decorator.addEventListener("mouseleave", (_e) => {
    animation.reverse();
  })
  form.appendChild(decorator);
  console.log(form, position)
}

/**
 * 检索表单详细信息
 * @param form
 */
function retrieveFormInfo(form: HTMLFormElement) {
  console.log(form)
}

/**
 * 渲染表单填充按钮
 */
function renderFormDecorators() {
  const forms = retrieveBodyForm();

  forms.forEach(form => {
    decoratorForm(form, Direction.Down)
  })
}

renderFormDecorators();
window.onresize = () => {
  renderFormDecorators();
}
